package team.nmsg.ge.system.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import team.nmsg.ge.system.exception.SysBusinessException;

/**
 * 在传统的spring mvc程序里会有两个WebApplicationContext，
 * 一个是parent，从applicationContext.xml里加载的，一个是child，从servlet-context.xml里加载的。
 * 两者是继承关系，child WebApplicationContext 可以通过getParent()函数获取到root
 * WebApplicationContext。
 * 
 * 简单地说child WebApplicationContext里的bean可以注入root WebApplicationContext里的bean，
 * 而parent WebApplicationContext的bean则不能注入child WebApplicationContext里的bean。
 * 
 * @author Guodeqi
 *
 */
@Component
public class SysSpringContext implements ApplicationContextAware{
	private static final Logger log = LoggerFactory.getLogger(SysSpringContext.class);
	
	private static ApplicationContext appContext ;
	
	@Override
	public void setApplicationContext(ApplicationContext arg0)
			throws BeansException {
		appContext = arg0;
	}
	
	
	public static<T> T getService(Class<T> clazz ){
		
		T bean = null;
		try {
			String name = clazz.getName();
			if( !name.toLowerCase().endsWith("service") ){
				throw new SysBusinessException("You must get a service bean!");
			}
			
			bean = appContext.getBean(clazz);
		} catch (Exception e) {
			log.error("" ,e );
		}
		return bean;
	}
	
	public static ApplicationContext getAppContext(){
		return appContext;
	}
	
	

}
